import { Component, toNative, Ref } from 'vue-facing-decorator'
import Render from '@/render/Render'
import BackgroundImage from '../assets/login/bg-image.png'
import Logo from '../assets/logo.png'
// import { select } from '@/components/low-code/components/Common'
import { login, getCaptchaImage, sendVefifyCode } from '@/api/login/index'
import type { PasswordLoginReqDto } from '@/api/login/types'
import SliderVerify from '@/components/slider-verify/SliderVerify'

import {
    getModelValue,
    renderForm,
    initModelValue,
    type FormModalDto
} from '@/components/modal/Modal'
import userStore from '@/stores/user'
import router from '@/router'
import styled from 'vue3-styled-components'
import { shake, wait } from '@/utils/util'
import styles from './login.module.scss'
import user from '@/stores/user'
import { EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons-vue'
import { Button, Card, message } from 'ant-design-vue'

@Component
export class LoginRender extends Render {
    @Ref formRef: undefined

    isClick = false
    isRemember = false
    formConfig = this.initFormConfig() as FormModalDto
    passwordFormConfig = this.initPasswordFormConfig() as FormModalDto

    active = 'fastLogin'

    eyeOpen = false

    verifyCodeImg = ''
    uuid = ''

    showVerify = false

    countSeconds = 60
    canClickCount = true
    timer = 0

    initFormConfig() {
        return {
            show: true,
            title: '',
            theme: 'dark',
            params: {
                size: 'large'
            },
            items: {
                username: {
                    name: '',
                    element: 'input',
                    placeholder: '请输入手机号',
                    value: '17621547855',
                    required: true
                },
                verifyCode: {
                    name: '',
                    element: 'input',
                    type: 'password',
                    placeholder: '请输入密码',
                    required: true,
                    params: {
                        append: () => (
                            <Button onClick={this.onGetVerifyCode} type="primary">
                                { this.canClickCount ? '获取验证码' : `${this.countSeconds}秒后重新获取` }
                            </Button>
                        )
                    }
                }
            },
            complete: () => {
                this.onFastSubmit()
            },
            cancel: () => {}
        } as FormModalDto
    }
    loginForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    initPasswordFormConfig() {
        return {
            show: true,
            title: '',
            theme: 'dark',
            params: {
                size: 'large'
            },
            items: {
                username: {
                    name: '',
                    element: 'input',
                    placeholder: '请输入手机号',
                    value: '17621547855',
                    required: true
                },
                password: {
                    name: '',
                    element: 'input',
                    type: 'password',
                    placeholder: '请输入密码',
                    value: 'lthd@2021.03',
                    required: true,
                    params: {
                        append: () =>
                            this.eyeOpen ? (
                                <view class="cursor-pointer" onClick={this.onHandleEyeOpen}>
                                    <EyeOutlined />
                                </view>
                            ) : (
                                <view class="cursor-pointer" onClick={this.onHandleEyeOpen}>
                                    <EyeInvisibleOutlined />
                                </view>
                            )
                    }
                },
                code: {
                    name: '',
                    element: 'input',
                    placeholder: '请输入图形验证码',
                    required: true,
                    class: styles['reset-append-padding'],
                    params: {
                        suffix: () => (
                            <img
                                class={'cursor-pointer h-42px w-[120px]'}
                                src={this.verifyCodeImg}
                                onClick={this.getCaptchaImage}
                            ></img>
                        )
                    }
                }
            },
            complete: () => {
                this.onSubmit()
            },
            cancel: () => {}
        } as FormModalDto
    }

    passwordLoginForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    // 快捷登录点击获取验证码打开图形验证码
    onGetVerifyCode() {
        if (!this.canClickCount) return
        const data = getModelValue(this.formConfig) as PasswordLoginReqDto

        if (!data.username) {
            message.error('请输入手机号')
            return
        } else if (data.username?.length !== 11) {
            message.error('请输入正确的手机号')
            return
        }
        this.showVerify = true
    }

    // 图形验证通过后发送短信验证码
    async onVerifyed() {
        const data = getModelValue(this.formConfig) as PasswordLoginReqDto
        const res = await sendVefifyCode({
            phone: data.username,
            passCard: this.createCode()
        })
        this.onCountDown()
    }

    /**
     * 生成随机代码
     *
     * @returns 返回生成的随机代码
     */
    createCode() {
        let code = ''
        const codeLen = 6
        const random = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2]
        for (let i = 0; i < codeLen; i++) {
            code += random[Math.floor(Math.random() * 10)]
        }
        return code
    }

    /**
     * 倒计时函数
     *
     */
    onCountDown() {
        if (!this.canClickCount) return
        this.canClickCount = false
        this.countSeconds--
        this.timer = setInterval(() => {
            this.countSeconds--
            if (this.countSeconds <= 0) {
                clearInterval(this.timer)
                this.canClickCount = true
                this.countSeconds = 60
            }
        }, 1000)
    }

    // 快捷登录
    async onFastSubmit() {
        shake(async () => {
            await this.loginForm.validate()
            const user = userStore()
            user.token = ''
            const data = getModelValue(this.formConfig)
            data.loginType = 1
            data.platFrom = 2
            const loginData = await login(data)
            await user.login(loginData?.token)
            this.$nextTick(() => {
                router.push('/customer/list')
            })
        })
    }


    // 密码登录
    async onSubmit() {
        shake(async () => {
            await this.passwordLoginForm.validate()
            const user = userStore()
            user.token = ''
            const data = getModelValue(this.passwordFormConfig) as PasswordLoginReqDto
            data.platFrom = 2
            if (this.active === 'passwordLogin') {
                data.uuid = this.uuid
            }
            const loginData = await login(data).catch((err) => {
                this.getCaptchaImage()
            })
            await user.login(loginData?.token)            
            this.$nextTick(() => {
                router.push('/')
            })
        }, 300)
    }

    onSavePassword(ev: boolean) {
        if (ev) {
            const data = getModelValue(this.formConfig)
            if (Object.values(data).every((i) => i)) {
                localStorage.setItem('savedLoginPassword', JSON.stringify(data))
            }
        } else {
            localStorage.removeItem('savedLoginPassword')
        }
    }

    toggleLoginType(type: string) {
        this.active = type
    }

    onHandleEyeOpen() {
        this.eyeOpen = !this.eyeOpen
        this.passwordFormConfig.items!.password!.type = this.eyeOpen ? 'text' : 'password'
    }

    async getCaptchaImage() {
        const res = await getCaptchaImage()
        this.verifyCodeImg = 'data:image/png;base64,' + res.img
        this.uuid = res.uuid
    }

    logout() {
        userStore().logout()
    }

    onCloseVerify() {
        this.showVerify = false
    }

    onMounted() {
        this.loginForm = renderForm(this.formConfig)
        this.passwordLoginForm = renderForm(this.passwordFormConfig)

        this.getCaptchaImage()

        const savedLoginPassword = localStorage.getItem('savedLoginPassword')

        this.isRemember = !!savedLoginPassword

        if (savedLoginPassword) {
            initModelValue(this.formConfig, JSON.parse(savedLoginPassword))
        }
    }

    // renderFrom() {
    //     return (
    //         <this.styleEl class="login-box fixed right-32 top-1/2 transform -translate-y-1/2">
    //             <div class="text-lg text-blue-dark-100 mt-32 relative inline-block pb-4 after:content-DEFAULT after:block after:absolute after:bottom-0 after:left-1/2 after:transform after:-translate-x-1/2 after: after:w-3 after:h-0.5 after:bg-blue-dark-100">
    //                 用户登录
    //             </div>
    //             {this.loginForm.element()}
    //             <ElButton
    //                 size="large"
    //                 round
    //                 class={`w-full mt-20 text-lg !text-white !bg-blue-dark-100 ${styles['login']}`}
    //                 onClick={this.onSubmit}
    //             >
    //                 登录
    //             </ElButton>
    //         </this.styleEl>
    //     )
    // }

    renderFrom() {
        return (
            <Card
                class="w-530px fixed right-32 top-1/2 transform -translate-y-1/2"
            >
                <div class="flex justify-around text-18px">
                    <div
                        onClick={() => this.toggleLoginType('fastLogin')}
                        class={[this.active === 'fastLogin' ? 'font-bold' : '', 'cursor-pointer']}
                    >
                        快捷登录
                    </div>
                    <div
                        onClick={() => this.toggleLoginType('passwordLogin')}
                        class={[
                            this.active === 'passwordLogin' ? 'font-bold' : '',
                            'cursor-pointer'
                        ]}
                    >
                        密码登录
                    </div>
                </div>
                {this.active === 'fastLogin' ? this.renderFastLogin() : this.renderPasswordLogin()}
            </Card>
        )
    }

    renderFastLogin() {
        return this.showVerify ? (
            <SliderVerify onClose={this.onCloseVerify} onVerified={this.onVerifyed} />
        ) : (
            <div class="mt-20">
                {this.loginForm.element()}
                <Button
                    size="large"
                    class={`w-full mt-20 text-lg !text-white !bg-blue-100 ${styles['login']}`}
                    onClick={this.onFastSubmit}
                >
                    登录
                </Button>
            </div>
        )
    }

    renderPasswordLogin() {
        return (
            <div class="mt-20">
                {this.passwordLoginForm.element()}
                <Button
                    size="large"
                    class={`w-full mt-20 text-lg !text-white !bg-blue-100 ${styles['login']}`}
                    onClick={this.onSubmit}
                >
                    登录
                </Button>
            </div>
        )
    }

    render() {
        return (
            <div
                class="h-screen bg-cover bg-no-repeat bg-center border-blue-gray-50 min-w-[720px]"
                style={`background-image: url(${BackgroundImage})`}
            >
                <img onClick={this.logout} class="pl-20px pt-20px" src={Logo} alt="" />
                {this.renderFrom()}
            </div>
        )
    }
}

export default toNative(LoginRender)
